package com.netty.rpc.register;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * Created by XiongMM on 2017/11/23.
 */
public class RpcRegistry {

    private int port;

    public RpcRegistry(int port){
        this.port=port;
    }
    public void start(){
        //NioEventLoopGroup是线程组，包含了一组NIO线程，专门用于网络事件的处理。其实也是：Reactor线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //bossGroup用于服务端接收客户端的链接，workerGroup用于进行SocketChannel的网络读写
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //用于启动NIO服务端的辅助启动类
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    //与客户端不同哈
                    .channel(NioServerSocketChannel.class)
                    //配置TCP参数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //设置用于处理网络I／O事件，比如消息解码，记录日志等
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4,0,4));
                            pipeline.addLast(new LengthFieldPrepender(4));
                            pipeline.addLast("encoder", new ObjectEncoder());
                            pipeline.addLast("decoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
                            pipeline.addLast("handler", new RegistryHandler());
                        }
                    });
            //同步阻塞，绑定端口，防止端口被竞争绑定；
            ChannelFuture channelFuture = b.bind(this.port).sync();
            System.out.println("RPC registry start listen port :" + port);
            channelFuture.channel().closeFuture().sync();
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args){
        new RpcRegistry(8080).start();
    }
}
